# from machine import Pin, I2C
import machine
import time
import ntptime

import network

import _thread

# import urequests

###########
import agent
import web_server

import tools

TIMEZONE=8
TIME_RESET_HOUR=3
TIME_RESET_MINUTE=30
TIME_RESET_WEEK=2 # 0 == 周1
tools.init(TIME_RESET_HOUR,TIME_RESET_MINUTE,tz=TIMEZONE)

PIN_RedLed0 = 12
PIN_RedLed1 = 13
#////////////////////////
# adc 0 1 2 3 4

# temperature
PIN_ADC_T = 3
# Hight
PIN_AC1 = 6
PIN_AC2 = 7
PIN_ADC_H = 2

# relay FOR heating (GPIO 11  false=2.8v??? 换成gpio 4|5)
PIN_HEATING = 5

# mosfet , 12v for water feeding.
PIN_WATERFEED = 10


ssid="xxxxhbxxxx"
passwd="8888888888"
wifi_conneted=False
ntptime.host = "ntp.lan"


##
def try_import_ap():
    try:
        import set_ap
        set_ap.start()
    except Exception as e:
        print("[E] import ap error:",e)

## network and ntp
def do_connect():
    global wifi_conneted
    print("[info] in network thread")
    wlan = network.WLAN(network.STA_IF)
    count=0

    def _connect():
        nonlocal count
        if not wlan.isconnected():
            count+=1
            print('[i] connecting to network...%d'%count)
            wlan.active(True)
            wlan.connect(ssid, passwd)
            for _ in range(10):
                if wlan.isconnected():
                    print('network config:', wlan.ifconfig())
                    return True
                time.sleep(1)
            return False
        else:
            return True
    
    while True:
        if _connect():
            time.sleep(3)
            print('network config:', wlan.ifconfig())
            tools.update_time()
            wifi_conneted=True
            break
        time.sleep(25)
    
    while True:
        _connect()
        time.sleep(30)

    

def job_web_server(my_agent):
    while True:
        if wifi_conneted:
            break
        time.sleep(10)
    web_server.start(my_agent)
    #################


def init_all():
    # wifi
    try_import_ap()
    _thread.start_new_thread(do_connect,())
    for _ in range(10):
        t=tools.gmtime()
        if tools.isUpdated(t):
            break
        time.sleep(4)
    agent.init_agent()
    for _ in range(3):
        if agent.get_agent() is None:
            print("[E] agent init error" )
            time.sleep(2)
        else:
            break

def start_threads():
    for _ in range(20):
        if agent.get_agent():
            _thread.start_new_thread(agent.get_agent().job_daily,())
            _thread.start_new_thread(agent.get_agent().job_update,())
            _thread.start_new_thread(job_web_server,(agent.get_agent(),))
            print("[OK] agent.get_agent is inited")
            break
        else:
            print("[Warn] agent.get_agent == None")
        time.sleep(2)



class PostJobs():
    LOOPCOUNT=0
    def __init__(self):
        self.LOOPCOUNT=0

    # sleep的目的: 这样时间都是差不多 3:30am
    def sleep_pre_reboot(self,t_hour,t_min):
        minute=(TIME_RESET_HOUR-t_hour)*60 + TIME_RESET_MINUTE-t_min
        if minute>0:
            if minute>121:
                return False
            # 18秒 是预设 重启时间
            sec=minute*60-18
            if sec<1:
                sec=1
            time.sleep(sec)
        return True

    def do_reboot(self):
        if self.LOOPCOUNT <4:
            return
        
        t=tools.localtime()
        year=tools.get_year(t)
        weekday=tools.get_weekday(t)
        hour=tools.get_hour(t)  # t[3]+8-24 #+8 timezone
        minute=tools.get_minute(t)
        # a day = 86400 sec; 150hour~=6.25day

        # year>2022 判断为 时间已更新!
        if (tools.isUpdated(t) or self.LOOPCOUNT>240):
            if weekday == TIME_RESET_WEEK:
                # 0 == Monday ,  1周1次重启
                if hour==TIME_RESET_HOUR-1 or hour==TIME_RESET_HOUR:
                    # do_reset(hour,minute)
                    if self.sleep_pre_reboot(hour,minute):
                        machine.reset()      
                
    def start(self):
        while True:
            try:
                tools.update_time()
            except Exception as e:
                print("[E|W] update time error",e)
            # 1hour
            time.sleep(3600)
            self.LOOPCOUNT+=1
            if self.LOOPCOUNT<4:
                # 4小时内 不执行, 防止 一小时内重复执行!!
                continue

            try:
                self.do_reboot()
            except Exception as e:
                print("[E] do_reboot error",e)

    
        
        

#####################
init_all()
start_threads()

post=PostJobs()
post.start()



# led1=Pin(12,Pin.OUT)
# led2=Pin(13,Pin.OUT)




# print(time.time())
# print(time.gmtime())
# print(time.localtime())
# print(tools.localtime())
# led1.on()
# time.sleep(1)
# led1.off()
# led2.on()
# time.sleep(10)
# led2.off()
# print("xxx")
# print(machine.freq())
